package br.com.news.web.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.news.utils.database.beans.enums.Perfil;
import br.com.news.web.BaseMB;
import br.com.news.web.ManagedBeanAccess;
import br.com.news.web.annotations.Permission;
import br.com.news.web.session.UserSession;

public class PermissionFilter implements Filter {

	@Autowired
	private UserSession userSession;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String[] url = req.getRequestURL().toString().split("/");

		ManagedBeanAccess beanAccess = ManagedBeanAccess.fromRoute(url[url.length - 1]);

		if (beanAccess != null) {
			Class<? extends BaseMB> clazz = beanAccess.managedBean();
			Permission permission = clazz.getAnnotation(Permission.class);

			if (permission != null) {
				Perfil[] perfils = permission.profile();

				if (perfils.length == 0 && userSession.isLogged()) {
					res.sendRedirect(req.getContextPath()+"/index.xhtml");
					return;
				} else if (perfils.length > 0) {

					if (!userSession.isLogged()) {
						res.sendRedirect(req.getContextPath()+"/index.xhtml");
						return;
					}

					if (!Arrays.asList(perfils).contains(userSession.perfil())) {
						res.sendRedirect(req.getContextPath()+"/index.xhtml");
						return;
					}
				}

			}
		}

		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	public void setUserSession(UserSession userSession) {
		this.userSession = userSession;
	}

}
